#include "connectorsystem.h"
#include "../entities/pinentity.h"
#include <QDebug>
#include <QCursor>
#include <QGraphicsView>
#include <QGraphicsItem>
#include "../aurasim.h"

ConnectorSystem::ConnectorSystem(QObject *parent): System (parent)
{
    initConnections();
    mSelectedPin = nullptr;
}

void ConnectorSystem::initConnections()
{
    connect(Aurasim::entityManager().data(), &EntityManager::entityAdded, [=](Entity* entity){
        connect(entity, &Entity::selected, this, &ConnectorSystem::onItemSelected);
        connect(entity, &Entity::diselected, this, &ConnectorSystem::onItemDiselected);
        foreach (QGraphicsItem* child, entity->childItems()){
            Entity* childEntity = static_cast<Entity*>(child);
            if(childEntity){
                connect(childEntity, &Entity::selected, this, &ConnectorSystem::onItemSelected);
                connect(childEntity, &Entity::diselected, this, &ConnectorSystem::onItemDiselected);
            }
        }
    });

}

void ConnectorSystem::onItemSelected(Entity *entity)
{
    // return handling if selected entities's count is up to 2
    if (Aurasim::selectedEntities().count() > 2 || Aurasim::mouseDraggingState())
        return;

    PinEntity* pin = qobject_cast<PinEntity*>(entity);
    if(!pin) {
        if(mSelectedPin)
            mSelectedPin = nullptr;
        return;
    }

    if(!mSelectedPin) {
        mSelectedPin = pin;
        return;
    }

    if(mSelectedPin && mSelectedPin != pin){
        // cannot connect with two same pin mode's pins
//        if(
//                mSelectedPin->pinMode() == pin->pinMode() ||
//                (mSelectedPin->pinMode() == 0 && pin->pinMode() == 2) ||
//                (mSelectedPin->pinMode() == 2 && pin->pinMode() == 0)
//                ) {

//            mSelectedPin = pin;
//            qDebug() << "cannot connect with two same pin mode's pins" <<  mSelectedPin << "," << pin;
//            return;
//        }
        connectPin(mSelectedPin, pin);
    }

}

void ConnectorSystem::onItemDiselected(Entity *entity)
{
    Q_UNUSED(entity)
}

void ConnectorSystem::connectPin(PinEntity *startPin, PinEntity *endPin)
{
//    if(startPin->isConnected() || endPin->isConnected())
//        return;

    Entity* e = new ConnectorEntity(nullptr, startPin, endPin);
    Aurasim::entityManager()->addEntity(e);
    e->setZValue(100);
    mSelectedPin = nullptr;
}

